﻿using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.UserRoleCommand;
using RBAC_Uthorization.Read.API.DTO;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.UserRoleHandler
{
    public class UserRoleShowCommandHandlers : IRequestHandler<UserRoleUserIdCommand, ApiResult<List<int>>>
    {
        private readonly ILogger<UserRoleShowCommandHandlers> _logger;
        private readonly IUserRoleRepository _userRoleRepository;

        public UserRoleShowCommandHandlers(ILogger<UserRoleShowCommandHandlers> logger, IUserRoleRepository userRoleRepository)
        {
            _logger = logger;
            _userRoleRepository = userRoleRepository;
        }

        public async Task<ApiResult<List<int>>> Handle(UserRoleUserIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var userIds = new HashSet<int>();
                var userRolelist = await _userRoleRepository.GetAllAsunc(x => x.role_id == request.id && x.del_flag == 0);
                if (userRolelist != null)
                {
                    foreach (var item in userRolelist)
                    {
                        userIds.Add(item.user_id);
                    }
                }
                return new ApiResult<List<int>>() { Data = userIds.ToList() };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "用户角色id反填异常");
                return new ApiResult<List<int>>() { Code = ResultCode.Fail, Message = "用户角色异常" };
            }
        }
    }
}
